Element only Navigation
Element-only navigation in JavaScript allows you to move between elements in the DOM without relying on classes, IDs, or other attributes. Instead, you can use element properties such as:
Accessing Parent, Children, and Siblings
JavaScript provides various properties to navigate between elements:
parentElement: Get the parent of an element.
children: Get all child elements.
firstElementChild: Get the first child element.
lastElementChild: Get the last child element.
nextElementSibling: Get the next sibling element.
previousElementSibling: Get the previous sibling element.
First Child vs First Element Child
There is a difference between firstChild and firstElementChild. firstChild returns the first child node, which can be a text node or an element. firstElementChild returns the first child element , which is always an element node.
Example
Let's consider the following HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio Website</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js">
<style>
html, body{
margin:0;
padding: 0;
height: 100%;
width: 100%;
}
ul{
display: flex;
background: cyan;
margin: 0;
padding: 10px 0;
}
ul li{
list-style: none;
margin: 0 25px;
}
</style>
</head>
<body> <!-- this is a comment -->
<nav>
<ul>
<li>Home</li>
<li>About us</li>
<li>Services</li>
<li>My Gear</li>
</ul>
</nav>
<h1>Hi it's Me</h1>
<script>
let b = document.body
console.log("First child of b is:", b.firstChild) <!-- It can be text Node, Comment Node -->
console.log("First Element child of b is:", b.firstElementChild) <!-- It gives the First HTML chunk of Body -->
</script>
</body>
</html>
Conclusion
Here, we have seen how to get the first child and first element child of a node in JavaScript. The first child of a node can be a text node or a comment node, while the first element child of a node is the first HTML element of the node.